package com.dqlp.yf.rabbitmq.sender;

import com.dqlp.yf.rabbitmq.bean.Order;
import com.dqlp.yf.rabbitmq.constant.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: rabbitmq
 * @description:
 * @author: andy
 * @create: 2019-09-09 11:09
 */
@Component
@Slf4j
public class FanoutSender implements RabbitTemplate.ReturnCallback,RabbitTemplate.ConfirmCallback {

    final
    RabbitTemplate rabbitTemplate;

    @Autowired
    public FanoutSender(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnCallback(this::returnedMessage);
        this.rabbitTemplate = rabbitTemplate;
    }

    public void fanoutSender(Order order) {
        CorrelationData correlationData = new CorrelationData(order.getId().toString());
        rabbitTemplate.convertAndSend(MqConstant.FANOUT_EXCHANGE,null,order,correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        if (ack) {
            log.info("fanout_exchange 收到成功 correlationData："+correlationData);
        } else {
            log.info("fanout_exchange 收到失败 correlationData："+correlationData);
        }

    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("从交换机 fanout_exchange 到队列失败时 message:{},replyCode:{},replyText:{},exchange:{},routingkey:{}",message,replyCode,replyText,exchange,routingKey);
    }
}
